<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>方法</title>
	<!--<script src="https://cdn.cdnjsdelivr.net/npm/vue/dist/vue.js"></script>-->
</head>
<body>
	<script>
		//'use strict';
		//在对象中绑定一个函数，称作这个对象的方法。
		var xiaohua = {
			name:"小明",
			birth:1993,
			age:function () {
				var y = new Date().getFullYear();
				//this关键字，始终指向当前对象。即xiaohua
				//在strict模式下this指向undefined
				return y - this.birth;
			}
		}

		console.log("小花的年龄为:" + xiaohua.age());

		//将age函数分开赋值
		// function getAge() {
		// 	var y = new Date().getFullYear();
		// 	return y - this.birth;
		// }

		// var xiaohong = {
		// 	name:"小红",
		// 	birth:1998,
		// 	age:getAge()
		// }
		//单独效用getAge()函数，this指向全局对象window
		//在strict模式下，this指向undefined
		//console.log("单独调用ageAge()函数:" + getAge());
		//console.log("在xiaohong对象中调用age:" + xiaohong.age)

		var xiaobei = {
			name:"xiaobei",
			birth:1996,
			age:function () {
				var y = new Date().getFullYear();
				//在strict模式下this指向undefined;
				return y - this.birth;
			}
		}
		var f = xiaobei.age;
		console.log("小北1的年龄为:" + f());

		var xiaobei2 = {
			name:"xiaobei2",
			birth:1997,
			age:function () {
				//this在age函数内指向xiaobei2对象
				//this在age函数内的getAgeFromBirth内，指向undefined
				function getAgeFromBirth() {
					var y = new Date().getFullYear();
					return y - this.birth;
				}
				return getAgeFromBirth();
			}
		}
		var f2 = xiaobei2.age;
		console.log("小北2的年龄为:" + f2());

		var xiaobei3 = {
			name:"xiaobei3",
			birth:1999,
			age:function () {
				//this在age函数内指向xiaobei2对象
				//this在age函数内的getAgeFromBirth内，指向undefined
				var that = this;
				function getAgeFromBirth() {
					var y = new Date().getFullYear();
					return y - that.birth;
				}
				return getAgeFromBirth();
			}
		}
		console.log("小北3的年龄为:" + xiaobei3.age());

		//在独立的函数调用中，在strict模式下this指向undefined 非strict下指向window
		//可以根据函数的apply指定this的指向
		function getAge2() {
			let y = new Date().getFullYear();
			return y - this.birth;
		}

		var xiaozhang;
		xiaozhang = {
			name: "小张",
			birth: 1990,
			age: getAge2
		};

		console.log("getAge2():" + getAge2());
		console.log("getAge2.()" + getAge2.apply(xiaozhang,[]));
		//apply() 将参数打包成Array
		//call()  接受顺序传入的参数
		var number1= Math.max.apply(null,[3,4,6]);
		var number2 = Math.max.call(null,3,4,7);
		var number3 = Math.max(1,2,5);
		console.log("number1:" + number1);
		console.log("number2:" + number2);
		console.log("number3:" + number3);
		//装饰器
		//JavaScript 所有对象都是动态的，即使是内置的函数，也可以重新指向新的函数
		var count = 0;
		var oldParseInt = window.parseInt;
		window.parseInt = function () {
			count+=1;
			oldParseInt(arguments);
		}
		parseInt('10');
		parseInt('20');
		parseInt('30');
		console.log("count=" + count);
		window.parseInt = oldParseInt;
		parseInt('10');
		parseInt('20');
		parseInt('30');
		console.log("count=" + count);

	</script>
</body>
</html>